package com.rfid.system.service.impl;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.rfid.common.constant.UserConstants;
import com.rfid.common.exception.BusinessException;
import com.rfid.common.utils.DateUtils;
import com.rfid.common.utils.StringUtils;
import com.rfid.system.service.common.CodeRfidGenerateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rfid.system.mapper.TCustomerInfoMapper;
import com.rfid.system.domain.TCustomerInfo;
import com.rfid.system.service.ITCustomerInfoService;
import com.rfid.common.core.text.Convert;

/**
 * 客户信息Service业务层处理
 *
 * @author ruoyi
 * @date 2020-11-09
 */
@Service
public class TCustomerInfoServiceImpl implements ITCustomerInfoService {

    private static final Logger log = LoggerFactory.getLogger(TCustomerInfoServiceImpl.class);


    public static final String REGEX_MOBILE = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";

    @Autowired
    private TCustomerInfoMapper tCustomerInfoMapper;

    @Autowired
    private CodeRfidGenerateService codeGenerateService;

    /**
     * 查询客户信息
     *
     * @param id 客户信息ID
     * @return 客户信息
     */
    @Override
    public TCustomerInfo selectTCustomerInfoById(Long id) {
        return tCustomerInfoMapper.selectTCustomerInfoById(id);
    }

    /**
     * 查询客户信息列表
     *
     * @param tCustomerInfo 客户信息
     * @return 客户信息
     */
    @Override
    public List<TCustomerInfo> selectTCustomerInfoList(TCustomerInfo tCustomerInfo) {
        return tCustomerInfoMapper.selectTCustomerInfoList(tCustomerInfo);
    }

    /**
     * 新增客户信息
     *
     * @param tCustomerInfo 客户信息
     * @return 结果
     */
    @Override
    public int insertTCustomerInfo(TCustomerInfo tCustomerInfo) {
        tCustomerInfo.setCreateTime(DateUtils.getNowDate());
        return tCustomerInfoMapper.insertTCustomerInfo(tCustomerInfo);
    }

    /**
     * 修改客户信息
     *
     * @param tCustomerInfo 客户信息
     * @return 结果
     */
    @Override
    public int updateTCustomerInfo(TCustomerInfo tCustomerInfo) {
        tCustomerInfo.setUpdateTime(DateUtils.getNowDate());
        return tCustomerInfoMapper.updateTCustomerInfo(tCustomerInfo);
    }

    /**
     * 删除客户信息对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTCustomerInfoByIds(String ids) {
        return tCustomerInfoMapper.deleteTCustomerInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除客户信息信息
     *
     * @param id 客户信息ID
     * @return 结果
     */
    @Override
    public int deleteTCustomerInfoById(Long id) {
        return tCustomerInfoMapper.deleteTCustomerInfoById(id);
    }

    /**
     * 导入用户数据
     *
     * @param cusList       客户数据列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName      操作用户
     * @return
     */
    @Override
    public String importUser(List<TCustomerInfo> cusList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(cusList) || cusList.size() == 0) {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int countFail=0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TCustomerInfo cus : cusList) {
            int count=0;
            String inertFlag="0";
            try {
                if(StringUtils.isEmpty(cus.getCusEmail())){
                    count++;
                    countFail++;
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、邮箱不能为空");
                    inertFlag="1";
                }
                if(!isEmail(cus.getCusEmail())){
                    count++;
                    countFail++;
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、邮箱格式不正确");
                    inertFlag="1";
                }
                if(StringUtils.isEmpty(cus.getCusPhone())){
                    if(count==0){
                        count++;
                        countFail++;
                    }
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手机号码不能为空");
                    inertFlag="1";
                }
                if (!isPhone(cus.getCusPhone())){
                    if(count==0){
                        count++;
                        countFail++;
                    }
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手机号格式不正确");
                    inertFlag="1";
                }
                    if(StringUtils.isNotEmpty(cus.getCusEmail())&&StringUtils.isNotEmpty(cus.getCusPhone())){
                    //校验邮箱不能重复
                    TCustomerInfo infoEmail=new TCustomerInfo();
                    infoEmail.setCusEmail(cus.getCusEmail());
                    String emailFlag=this.checkEmailUnique(infoEmail);
                    if(UserConstants.USER_EMAIL_NOT_UNIQUE.equals(emailFlag)){
                        if(count==0){
                            count++;
                            countFail++;
                        }
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、邮箱重复");
                        inertFlag="1";
                    }
                    //校验手机号码不能为空
                    TCustomerInfo infoPhone=new TCustomerInfo();
                    infoPhone.setCusPhone(cus.getCusPhone());
                    String phoneFlag=this.checkPhoneUnique(infoPhone);
                    if(UserConstants.USER_PHONE_NOT_UNIQUE.equals(phoneFlag)){
                        if(count==0){
                            count++;
                            countFail++;
                        }
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、手机号码重复");
                        inertFlag="1";
                    }
                    if(phoneFlag.equals(UserConstants.USER_PHONE_UNIQUE)&&emailFlag.equals(UserConstants.USER_EMAIL_UNIQUE)&&inertFlag.equals("0")){
                        TCustomerInfo lastData=this.getLastData();
                        String cstno=codeGenerateService.generateCode("CUSTOMER_CODE_RULE",lastData.getCstno(),lastData);
                        cus.setCstno(cstno);
                        cus.setCreateTime(new Date());
                        cus.setUpdateTime(new Date());
                        cus.setCreateBy(operName);
                        this.insertTCustomerInfo(cus);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "客户编号 " + cus.getCstno() + " 导入成功");
                    }
                }

            } catch (Exception e) {
                if(count==0){
                    count++;
                    countFail++;
                }
                failureNum++;
                String msg = "<br/>" + failureNum + "客户编号 " + cus.getCstno() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + countFail + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验手机号码是否一致
     * @param tCustomerInfo
     * @return
     */
    @Override
    public String checkPhoneUnique(TCustomerInfo tCustomerInfo) {
        TCustomerInfo info=tCustomerInfoMapper.checkPhoneUnique(tCustomerInfo.getCusPhone());
        if (StringUtils.isNotNull(info)) {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验手机邮箱是否一致
     * @param tCustomerInfo
     * @return
     */
    @Override
    public String checkEmailUnique(TCustomerInfo tCustomerInfo) {
        TCustomerInfo info=tCustomerInfoMapper.checkEmailUnique(tCustomerInfo.getCusEmail());
        if (StringUtils.isNotNull(info)) {
            return UserConstants.USER_EMAIL_NOT_UNIQUE;
        }
        return UserConstants.USER_EMAIL_UNIQUE;

    }

    @Override
    public String checkUserName(TCustomerInfo tCustomerInfo) {
        TCustomerInfo info=tCustomerInfoMapper.checkUserName(tCustomerInfo.getUserName());
        if (StringUtils.isNotNull(info)) {
            return UserConstants.COMPANY_NAME_NOT_UNIQUE;
        }
        return UserConstants.COMPANY_NAME_UNIQUE;
    }

    /**

     * 判断是否是Email

     * @return

     */

    public static boolean isEmail(String email) {

        Pattern emailPattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

        Matcher matcher = emailPattern.matcher(email);

        if(matcher.find()){
            return true;
        }
        return false;

    }

    public static boolean isPhone(String phone){
        if(phone.length() != 11){
            return false;
        }
        String regex = "^[1][3,4,5,8][0-9]{9}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(phone);
        boolean isMatch = m.matches();
        if(isMatch){
           return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args){
        String phone="18280458545";
        String regex = "^[1][3,4,5,8][0-9]{9}$";
        Pattern p = Pattern.compile(regex);
         Matcher m = p.matcher(phone);
         boolean isMatch = m.matches();
         if(isMatch){
                 System.out.println("您的手机号格式正确");
         } else {
             System.out.println("您的手机号格式不正确");
         }

    }
    @Override
    public TCustomerInfo getLastData() {
        return tCustomerInfoMapper.getLastData();
    }
}
